const express = require("express");
const app = express();
const api = require("./routes/api");
const { auth } = require("./authController.cjs");
const cors = require("cors");
//const morgan = require("morgan");
//for log
const PORT = 3002;

//log
//app.use(morgan("tiny"));
//
// 允许 http://localhost:3000 访问资源
app.use(cors({ credentials: true, origin: true }));
// 放在路由处理之前
const allowList = [
  "http://localhost:50397",
  "http://192.168.2.127:3000",
  "http://localhost:3000",
];
app.use((req, res, next) => {
  console.log("from:", req.headers.origin);
  const allowIp = allowList.find((ip) => ip === req.headers.origin);
  res.header("Content-Type", "text/html; charset=utf-8");
  res.header("Access-Control-Allow-Origin", allowIp);
  res.header("Access-Control-Allow-Credentials", "true");
  res.header(
    "Access-Control-Allow-Methods",
    "GET, POST, OPTIONS, PUT, PATCH, DELETE",
    //"GET",
  );
  res.header(
    "Access-Control-Allow-Headers",
    "Content-Type, Authorization, custom-xxx",
  );
  res.header("Access-Control-Max-Age", "10");
  next();
});

app.use(express.json());
app.use(express.urlencoded({ extended: true }));
//
app.use(auth);
//
//app.use("/api/", require("./routes/api/login"));
api(app);

app.listen(PORT, () => {
  console.log(`  ---all Server is running on port ${PORT}`);
});
